import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'

export const useTabStore = defineStore('tabs', () => {
  const define = {
    active: '',
    tabs: [] as any[]
  }

  const tabs = ref(define)
  const addTab = (menu: any) => {
    tabs.value.active = menu.id
    for (let i = 0; i < tabs.value.tabs.length; i++) {
      const tab = tabs.value.tabs[i]
      if (tab.id == menu.id) {
        return
      }
    }
    tabs.value.tabs.push(menu)
  }

  //重置
  const reset = () => {
    tabs.value.tabs = []
    tabs.value.active = 'home'
    tabs
  }
  const removeTab = (key: any) => {
    console.log(key)
    tabs.value.tabs = tabs.value.tabs.filter(val => val.id != key)

    //被删除的不是当前激活标签不用管
    if (key != tabs.value.active) {
      return
    }

    //是的话则判断长度是否还有标签
    if (tabs.value.tabs.length != 0) {
      //激活最后一个标签
      const tab = tabs.value.tabs[tabs.value.tabs.length - 1]
      tabs.value.active = tab.name
      return
    }
    //最后指向首页
    tabs.value.active = 'home'
  }
  return { tabs, addTab, removeTab, reset }
}, {
  persist: {
    key: 'tabs',
    storage: localStorage
  }
})
